import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/user.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/call_uil.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/view/drive/contract_lock_page.dart';
import 'package:yuan_hang_app/views/mine/about_page.dart';
import 'package:yuan_hang_app/views/mine/edit_pass_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';
import 'package:http_parser/http_parser.dart';

import '../../base/base_state.dart';
import '../../http/app_response.dart';
import '../../widget/image_picker.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  BaseState<MinePage> createState() => _MinePageState();
}

class _MinePageState extends BaseState<MinePage> {
  User userInfo = User.fromJson2();

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        hideNavi: true,
        child: Column(
          children: [
            _topContent(),
            funItemView(
              'ic_mine_cards',
              '电子名片',
            ),
            funItemView(
              'ic_mine_passs',
              '修改密码',
            ),
            funItemView(
              'ic_mine_calls',
              '清理缓存',
            ),
            funItemView(
              'ic_mine_abouts',
              '关于APP',
            ),
            loginOut(),
          ],
        ));
  }

  Widget _topContent() {
    return Container(
      width: SizeUtils.screenW(),
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
            color: WColors.CDFEFFB,
            offset: const Offset(0, 1),
            blurRadius: 3.px),
      ], color: Colors.white),
      padding: EdgeInsets.symmetric(vertical: 30.px, horizontal: 15.px),
      margin: EdgeInsets.only(top: SizeUtils.statusBar(), bottom: 10.px),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              ImagePicker.showImagePicker(
                  context: context,
                  count: 1,
                  onSelected: (file) {
                    ///校验文件是否选中，如果文件未选中不调用上传接口
                    if (file[0] != null && file[0].length > 0) {
                      showLoading();
                      uploadImage(file[0]).then((value) {
                        if (value.resultCode == 200) {
                          String avatarUrl =
                              value.data["data"]["fileUploadUrl"];
                          Map param = {"headUrl": avatarUrl};
                          HttpUtils()
                              .post(Api.updateAvatar, data: param)
                              .then((value) {
                            hideLoading();
                            if (value.resultCode == 200) {
                              userInfo.headPortrait = avatarUrl;
                              SpUtil.remove(WConstant.USERINFO);
                              SpUtil.putString(
                                  WConstant.USERINFO, json.encode(userInfo));
                              setState(() {});
                            } else {
                              Toast.toast(value.errMsg);
                            }
                          });
                        } else {
                          Toast.toast(value.errMsg);
                        }
                      }).catchError((e) {
                        hideLoading();
                      });
                    }
                  });
            },
            child: ClipOval(
              child: StringUtils.safeGetValue(userInfo.headPortrait) == ""
                  ? Image.asset(
                      "images/head.png",
                      width: 68.px,
                      height: 68.px,
                      fit: BoxFit.cover,
                    )
                  : Image.network(
                      userInfo.headPortrait!,
                      width: 68.px,
                      height: 68.px,
                      fit: BoxFit.cover,
                    ),
            ),
          ),
          SizedBox(
            width: 20.px,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                StringUtils.safeGetValue(userInfo.employeeName),
                style: TextStyle(color: WColors.mainTextColor, fontSize: 18.px),
              ),
              SizedBox(
                height: 8.px,
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 5.px, vertical: 2.px),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.px),
                    color: WColors.primaryColor),
                child: Text(
                  "${StringUtils.safeGetValue(userInfo.shopName)} ${StringUtils.safeGetValue(userInfo.roleName)}",
                  style: TextStyle(color: WColors.white, fontSize: 12.px),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userInfo = WConstant().userInfo;
    setState(() {});
    print(User.userToJson(userInfo));
//    print(SpUtil.getString(WConstant.USERINFO));
  }

  base() {
    var content =
        utf8.encode("d6010c51e331c74637b4bd6e:0f16e0792d0aba5eb4397455");
    var digest = "Basic " + base64Encode(content);
    print(digest);
  }

  Widget funItemView(icon, title, {color}) {
    return GestureDetector(
        onTap: () {
          if (title == "电子名片") {
            base();
            getElectBusinessCard();
          } else if (title == "修改密码") {
            RouteHelper.pushWidget(context, const EditPassPage());
          } else if (title == "清理缓存") {
            WConstant.cleanList();
            CommonReqUtils.getSalesmanList();
            Toast.showLoading();
            CommonReqUtils.getDictList().then((v) {
              WConstant.initList();
              Toast.dismissLoading();
            });
          } else if (title == "关于APP") {
            RouteHelper.pushWidget(context, AboutPage());
            print("=============点击=======");
            //     RouteHelper.pushWidget(context,  ContractLocckPage(driveInfo: {}));
            // CommonReqUtils.getDictList();
            //     CommonReqUtils.getTagList();
          } else {
            Toast.toast("暂未开放!");
          }
        },
        child: Container(
            height: 48.px,
            padding: EdgeInsets.symmetric(horizontal: 20.px),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  bottom: BorderSide(
                    color: WColors.border, // 边框颜色
                    width: 0.5.px, // 边框宽度
                  ),
                )),
            child: Row(
              children: <Widget>[
                Image.asset(
                  'images/$icon.png',
                  width: 20.px,
                  height: 20.px,
                  color: color,
                ),
                Expanded(
                    child: Padding(
                  padding: EdgeInsets.only(
                    left: 14.px,
                  ),
                  child: WText(
                    title,
                    style: TextStyle(
                        fontSize: 16.px, color: WColors.mainTextColor),
                  ),
                )),
                Image.asset(
                  'images/ic_right.png',
                  width: 12.px,
                  height: 12.px,
                )
              ],
            )));
  }

  Widget loginOut() {
    return GestureDetector(
        onTap: () {
          CommonDialog.showConformDialog(
              context: context,
              title: "提示",
              content: "你确定要退出登录吗",
              onConfirm: (text) {
                CommonReqUtils.loginOut();
              });
        },
        child: Container(
            height: 48.px,
            margin: EdgeInsets.only(top: 20.px),
            alignment: Alignment.center,
            width: SizeUtils.screenW() - 40.px,
            padding: EdgeInsets.symmetric(horizontal: 20.px),
            decoration: BoxDecoration(
                //
                //     boxShadow: [
                //   BoxShadow(
                //       color: WColors.CDFEFFB,
                //       offset: const Offset(0, 1),
                //       blurRadius: 3.px),
                // ],
                border: Border.all(color: WColors.border, width: 1.px),
                borderRadius: BorderRadius.circular(5.px),
                color: Colors.white),
            child: WText(
              "退出登录",
              style: TextStyle(fontSize: 16.px, color: WColors.mainTextColor),
            )));
  }

  void getElectBusinessCard() {
    Toast.showLoading();
    HttpUtils().get(Api.getElectBusinessCard).then((data) {
      Toast.dismissLoading();
      if (data.resultCode == 200) {
        CommonDialog.showCardDialog(
            context: context, url: data.data, userInfo: userInfo);
      } else {
        Toast.toast(data.errMsg);
      }
    }).catchError((e) {
      Toast.dismissLoading();
    });
  }

  static Future<AppResponse> uploadImage(filePath) {
    FormData formData = FormData.fromMap({
      'file': MultipartFile.fromFileSync(filePath,
          contentType: MediaType.parse("image/jpeg"))
    });
    return HttpUtils().post(Api.uploadFile2, data: formData).then((onValue) {
      return onValue;
    });
  }
}
